package Java8.stramparalle;

import java.util.function.Function;
import java.util.stream.Stream;

public class TestStreamParalle {

    public static void main(String[] args) {
        System.out.println("1=>" + measureSumperf(TestStreamParalle::sequentialSum, 100000));
        System.out.println("1=>" + measureSumperf(TestStreamParalle::paralleSum, 100000));
    }

    public static long sequentialSum(Long n) {
        return Stream.iterate(1L, i -> i + 1).limit(n).reduce(0L, Long::sum);
    }

    public static long paralleSum(Long n) {
        return Stream.iterate(1L, i -> i + 1).limit(n).parallel().reduce(0L, Long::sum);
    }

    public static long measureSumperf(Function<Long, Long> adder, long n) {
        long fastest = Long.MAX_VALUE;

        for (int i = 0; i < 10; i++) {
            long start = System.nanoTime();

            long sum = adder.apply(n);
            long duration = (System.nanoTime() - start) / 1000000;

            System.out.println("result:" + sum);
            if (duration < fastest) {
                fastest = duration;
            }
        }
        return fastest;
    }
}
